import React, { Component ,createRef} from 'react'
import styles from './index.module.css'
import { PropTypes } from 'prop-types'

export default class Sticky extends Component {
  placeholder = createRef()
  content = createRef()

  //浏览器滚动事件
  handleScroll=()=>{
    
    const placeholderEl=this.placeholder.current
    const contentEl=this.content.current

    //占位元素的top值
    const {top} =placeholderEl.getBoundingClientRect()

    if(top<=0){
      placeholderEl.style.height=`${this.props.height}px` //吸顶的顺滑实现
      contentEl.classList.add(styles.fixed)
    }else{
      placeholderEl.style.height=`0px`//取消吸顶的顺滑实现
      contentEl.classList.remove(styles.fixed)
    }

  }

  componentDidMount(){
    window.addEventListener('scroll',this.handleScroll)
  }

  componentWillUnmount(){
    window.removeEventListener('scroll',this.handleScroll)
  }

  render() {
    return (
      <div>
        {/* 占位元素 */}
        <div ref={this.placeholder}/>

        {/* 内容元素 */}
        <div ref={this.content}>{this.props.children} </div>
      </div>
    )
  }
}

Sticky.propTypes = {
  height: PropTypes.number.isRequired,
};